package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.JwtUtils;
import com.itheima.common.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//定义一个类，实现一个标准的Filter过滤器的接口
@Slf4j
@WebFilter
public class DemoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("DemoFilter-------init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.contains("/login")) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = httpServletRequest.getHeader("token");
        if (!StringUtils.hasText(token)) {
            PrintWriter writer = httpServletResponse.getWriter();
            Result<?> error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            writer.write(json);
//            writer.write("{ \"code\": 0, \"msg\": \"NOT_LOGIN\", \"data\": null }");
            return;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            PrintWriter writer = httpServletResponse.getWriter();
//            writer.write("{ \"code\": 0, \"msg\": \"NOT_LOGIN\", \"data\": null }");
            Result<?> error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            writer.write(json);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {
        log.info("DemoFilter-------destroy");
    }
}